package com.jiyongjun.component.utils;

import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

/**
 * <h2></h2>
 * <h3>描述：</h3>
 *
 * @author yongjun.jyj
 * @since 2022/7/14 18:22
 */
public final class SpringElExpressionUtil {

    public static <T> T parseElExpression(Object[] args, Method method, String elExpression, Class<T> resultType) {
        Parameter[] parameters = method.getParameters();
        StandardEvaluationContext elContext = new StandardEvaluationContext();
        if (parameters != null && parameters.length > 0) {
            for (int i = 0; i < parameters.length; i++) {
                String paraName = parameters[i].getName();
                Object paraVal = args[i];
                elContext.setVariable(paraName, paraVal);
            }
        }
        SpelExpressionParser parser = new SpelExpressionParser();
        return parser.parseExpression(elExpression)
                .getValue(elContext, resultType);
    }

}
